var _ljs = require("../sever/mmlog").root("[routes/ticket.js]");
var express = require('express');
var router = express.Router();

var util = require("../sever/util");
var _dbTicket = require("../sever/db/ticket");
var _socket = require("../sever/socket");

function formate(data, res) {
	var _ = {
		total: 0,
		rows: []
	};
	if (data != -1) {
		_ = {
			total: data.length,
			rows: data
		}
	}
	res.json(_);
}

/**
 * 工单详情页面 
 */
router.get("/tail/:uuid", function(req, res, next) {
	var uuid = req.params.uuid;
	_dbTicket.selectTicketByUUID(uuid, function(data) {
		var result = data == -1 ? [{}] : data;
		result=result[0];
		
		if(result.CREATE_TIME){
			var _d=new Date(result.CREATE_TIME);
			result.CREATE_TIME=_d.toLocaleDateString()+" "+_d.toLocaleTimeString();
		}
		res.render("../client/plugins/ticket/views/ticket-detail.ejs", result);
	})
})

router.get('/goto/:uuid', function(req, res, next) {
	var uuid = req.params.uuid;
	_dbTicket.selectTicketByUUID(uuid, function(data) {
		if (data != -1 && data[0] && data[0].UUID) {
			res.json(result(0, data[0]))
		} else {
			res.json(result(1011004));
		}
	})

})

/**
 * 查询工单列表
 * 当jobId为ALL时、查询所有的工单、或者根据实际jobId查询工单
 */
router.get('/query/:jobId', function(req, res, next) {
	var id = req.params.jobId;
	var sort = req.query.sort,
		order = req.query.order;
	if (sort && order) {
		_dbTicket.selectTicketSort(id, sort, order,function(data){
			formate(data,res);
		})
	}else{
		_dbTicket.selectTicketByJobId(id, function(data){
			formate(data,res);
		})
	}
});

/**
 * 更新工单状态 
 */
router.get('/upstatus/:uuid/:value', function(req, res, next) {
	var id = req.params.uuid,
		status = req.params.value;
	_dbTicket.updateStatus(status, id, function(data) {
		if (data != -1) {
			res.json(util.result(0));
		} else {
			res.json(util.result(1011003));
		}
	})
});

router.post('/create', function(req, res, next) {
	var d = req.body;
	var p = [util.rid(), d.ticketId, d.author, d.customer, d.jobId, d.level, d.business, d.label, d.subject, d.content, d.files, new Date().getTime()];
	_dbTicket.insertTicket(p, function(data) {
		if (data != -1) {
			_socket.emit("ticketTip", {
				type: "new",
				content: "您有一条新工单任务"
			}, d.jobId);
			res.json(util.result(0));
		} else {
			res.json(util.result(1011003));
		}
	})
});

router.post('/mail/reply/:jobId/:ticketId', function(req, res, next) {
	var d = req.body;
	_dbTicket.replyMail(d, function(d) {
		res.json(d)
	})
});



module.exports = router;